package com.tjb.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjb.reggie.common.TjbException;
import com.tjb.reggie.entity.SetmealDish;
import com.tjb.reggie.entity.dto.SetmealDto;
import com.tjb.reggie.mapper.SetMealMapper;
import com.tjb.reggie.service.SetMealDishService;
import org.springframework.stereotype.Service;
import com.tjb.reggie.entity.Setmeal;
import com.tjb.reggie.service.SetMealService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author tjb
 * @version 1.0
 * @date 2022/8/25 12:19
 */
@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {
    /**
     * 套餐菜品业务
     */
    @Resource
    private SetMealDishService setMealDishService;
    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);
        //保存套餐和菜品的观联信息，操作setmeal，执行insert操作

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
            //设置setmealId
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setMealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐的基本信息和套餐下面的菜品
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIdsWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除
        List<Setmeal> setmeals = this.listByIds(ids);
        for (Setmeal setmeal : setmeals) {
            //如果不能删除，抛出异常
            if (setmeal.getStatus().equals(Integer.parseInt("1"))){
                throw new TjbException("删除的套餐中有正在售卖的，不能删除，请先停止售卖");
            }
        }
        //如果可以删除，先删除套餐表中的数据
        this.removeByIds(ids);
        //删除关系表中的数据
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SetmealDish::getSetmealId, id);
            setMealDishService.remove(wrapper);
        }
    }
}
